package com.itheima.reggie.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.UserHolder;
import com.itheima.reggie.domain.*;
import com.itheima.reggie.exception.CustomException;
import com.itheima.reggie.mapper.AddressMapper;
import com.itheima.reggie.mapper.OrderDetailMapper;
import com.itheima.reggie.mapper.OrderMapper;
import com.itheima.reggie.service.CartService;
import com.itheima.reggie.service.OrderService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

@Service
@Transactional
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Autowired
    private CartService cartService;
    @Autowired
    private AddressMapper addressMapper;

    @Autowired
    private OrderMapper orderMapper;

    @Override
    public void add(Order order) {

        //获取当前user
        User user = UserHolder.get();
        //获取user购物车
        List<Cart> list = cartService.findList();
        if(CollectionUtil.isEmpty(list)){
            throw new CustomException("购物车为空");
        }
        //获取前端传入的地址
        Address address = addressMapper.selectById(order.getAddressId());
        if(address == null){
            throw new CustomException("收货地址不存在");
        }
        /*手动生成id*/
        long id = IdWorker.getId();  //mybatisplus生成id

        BigDecimal total = new BigDecimal(0);
        //生成订单详情

        for (Cart cart : list) {
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setName(cart.getName());
            orderDetail.setOrderId(id);  //手动填充的订单id
            orderDetail.setDishId(cart.getDishId());
            orderDetail.setSetmealId(cart.getSetmealId());
            orderDetail.setDishFlavor(cart.getDishFlavor());
            orderDetail.setNumber(cart.getNumber());
            orderDetail.setAmount(cart.getAmount());
            orderDetail.setImage(cart.getImage());
            //保存到数据表
            orderDetailMapper.insert(orderDetail);

            //每次遍历，添加金额     total += amount * number
            total = total.add(cart.getAmount().multiply(new BigDecimal(cart.getNumber())));
        }
        //生成订单

        order.setId(id);
        order.setNumber(id+"");
        order.setStatus(1);
        order.setUserId(user.getId());
        order.setOrderTime(new Date());
        order.setCheckoutTime(new Date());
        order.setAmount(total);
        order.setUserName(user.getName());
        order.setPhone(address.getPhone());
        order.setAddress(address.getDetail());
        order.setConsignee(address.getConsignee());
        orderMapper.insert(order);


        //清空购物车
        cartService.clean();
    }

    /*分页查询订单   时间排序*/
    @Override
    public Page<Order> findLatest(Integer pageNum, Integer pageSize) {
        Page<Order> page = new Page<>(pageNum,pageSize);
        LambdaQueryWrapper<Order> wrapper = new LambdaQueryWrapper<>();
        wrapper.orderByDesc(Order::getOrderTime);
        Page<Order> page1 = orderMapper.selectPage(page, wrapper);
        List<Order> records = page1.getRecords();
        for (Order record : records) {
            LambdaQueryWrapper<OrderDetail> wrapper1 = new LambdaQueryWrapper<>();
            wrapper1.eq(OrderDetail::getOrderId,record.getId());
            List<OrderDetail> orderDetails = orderDetailMapper.selectList(wrapper1);
            record.setOrderDetails(orderDetails);
        }
        return page1;
    }

    @Override
    public Page<Order> findByPage(Integer pageNum, Integer pageSize,String number, String beginTime,String endTime) {
        Page<Order> page = new Page<>(pageNum,pageSize);

        LambdaQueryWrapper<Order> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(StringUtils.isNotEmpty(number),Order::getNumber,number)
                .between(beginTime != null && endTime!= null,Order::getOrderTime,beginTime,endTime);
        Page<Order> page1 = orderMapper.selectPage(page, wrapper);
        return page1;
    }
}
